package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;

import javax.print.DocFlavor;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Result;
import org.springframework.web.multipart.MultipartFile;
import com.example.springboot.entity.User;
import com.example.springboot.utils.TokenUtils;
import com.example.springboot.service.IUserService;

import com.example.springboot.service.IXCompanyService;
import com.example.springboot.entity.XCompany;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 客户管理 前端控制器
 * </p>
 *
 * @author
 * @since
 */
@RestController
@RequestMapping("/xCompany")
public class XCompanyController {

    @Resource
    private IXCompanyService xCompanyService;
    @Resource
    IUserService userService;

    private final String now = DateUtil.now();

    @PostMapping
    public Result save(@RequestBody XCompany xCompany) {
        if (xCompany.getId() == null) {
            //xCompany.setTime(DateUtil.now());
            //xCompany.setUserName(TokenUtils.getCurrentUser().getNickname());
            //xCompany.setUserId(TokenUtils.getCurrentUser().getId());
        }
        xCompanyService.saveOrUpdate(xCompany);
        return Result.success();
    }


    // 新增或者更新
    @PostMapping("/insertXCompany")
    public Result insertXCompany(@RequestBody XCompany xCompany) {
        if (xCompany.getId() == null) {
            //xCompany.setTime(DateUtil.now());
            //xCompany.setUserName(TokenUtils.getCurrentUser().getNickname());
            //xCompany.setUserId(TokenUtils.getCurrentUser().getId());
        }
        QueryWrapper<XCompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("client", xCompany.getClient());
//            数据库中存在数据的情况
        if (0 < Long.valueOf(xCompanyService.count(queryWrapper))) {
//            XCompany one = xCompanyService.getOne(queryWrapper);
//            List<String> changesList = new ArrayList<>();
//            try {
//                Class<?> clazz = xCompany.getClass();
//                List<Field> fields = Arrays.asList(clazz.getDeclaredFields());
//                for (Field field : fields) {
//                    field.setAccessible(true);
//                    Object value1 = field.get(xCompany);
//                    Object value2 = field.get(one);
//                    if (!Objects.equals(value1, value2)) {
//                        changesList.add("属性 " + field.getName() + " 的值发生了变化");
//                    }
//                }
////                for (String change : changesList) {
////                    System.out.println(change);
////                }
//                if (changesList.size()  >0) {
//                    xCompanyService.saveOrUpdate(xCompany);
//                    return Result.success();
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            return Result.error(Constants.CODE_400, "客户名称已经存在，请重新输入");
        }
//        数据库中未存在数据的状态
        xCompanyService.saveOrUpdate(xCompany);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        xCompanyService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        xCompanyService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(xCompanyService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(xCompanyService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(
            @RequestParam(defaultValue = "") String client,
            @RequestParam(defaultValue = "") String priority,
            @RequestParam(defaultValue = "") String type,
            @RequestParam(defaultValue = "") String bigModel,
            @RequestParam(defaultValue = "") String industry,
            @RequestParam(defaultValue = "") String area,
            @RequestParam(defaultValue = "") String ownbd,
            @RequestParam(defaultValue = "") String status,
            @RequestParam(defaultValue = "") String block,
            @RequestParam(defaultValue = "") String contractType,
            @RequestParam(defaultValue = "") String ownfae,
            @RequestParam(defaultValue = "") String currentStatus,
            @RequestParam(defaultValue = "") String hardType,
            @RequestParam(defaultValue = "") String startDate,
            @RequestParam(defaultValue = "") String endDate,
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam (defaultValue = "")String roleAdmin,
            @RequestParam (defaultValue = "")String userName
//            @RequestParam User user
            ) {

        System.out.println("userName                       "+userName);
//        System.out.println("user                       "+user);
        Page<XCompany> page = new Page<>(pageNum,pageSize);
        XCompany company = new XCompany();
        company.setClient(client);
        company.setPriority(priority);
        company.setType(type);
        company.setBigModel(bigModel);
        company.setIndustry(industry);
        company.setArea(area);
        company.setOwnbd(ownbd);
        company.setStatus(status);
        company.setBlock(block);
        company.setContractType(contractType);
        company.setOwnfae(ownfae);
        company.setCurrentStatus(currentStatus);
        company.setHardType(hardType);
        company.setStartDate(startDate);
        company.setEndDate(endDate);

//        如果登录用户不是管理元，只能查看自己名下的客户
        if (!StringUtils.isBlank(roleAdmin) && !roleAdmin.equals("ROLE_ADMIN")) {
            company.setOwnbd(userName);
        }

        IPage<XCompany> result = xCompanyService.selectByPage(page,company);
        return Result.success(result);
    }

    /**
    * 导出接口
    */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<XCompany> list = xCompanyService.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("XCompany信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

        }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<XCompany> list = reader.readAll(XCompany.class);

        xCompanyService.saveBatch(list);
        return Result.success();
    }

    private User getUser() {
        return TokenUtils.getCurrentUser();
    }

    // 新增或者更新
    @PostMapping("/updPublish")
    public Result updPublish(@RequestBody XCompany xCompany) {
        if (xCompany.getId() == null||xCompany.getIsPublish() == null) {
            return Result.error(Constants.CODE_500,"参数不全");
        }
        UpdateWrapper<XCompany> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", xCompany.getId());
        updateWrapper.set("is_publish",xCompany.getIsPublish());

//        数据库中未存在数据的状态
        xCompanyService.update(updateWrapper);
        return Result.success();
    }

    /**
     * 签约的算力金额
     */
    @GetMapping("/getContractAmount")
    public Result getContractAmount(String startDt,String endDt) {
        return Result.success(xCompanyService.getContractAmount(startDt,endDt));
    }

    /**
     * 签约率
     */
    @GetMapping("/getCompletionRate")
    public Result getCompletionRate(String startDt,String endDt) {
        return Result.success(xCompanyService.getCompletionRate(startDt,endDt));
    }

    /**
     * 200dk开发板金额和数量
     */
    @GetMapping("/get200dkAmountAndCount")
    public Result get200dkAmountAndCount(String startDt,String endDt) {
        return Result.success(xCompanyService.get200dkAmountAndCount(startDt,endDt));
    }

    /**
     * 大P带货金额
     */
    @GetMapping("/getDpdhAmount")
    public Result getDpdhAmount(String startDt,String endDt) {
        return Result.success(xCompanyService.getDpdhAmount(startDt,endDt));
    }

    /**
     * top10带货客户
     */
    @GetMapping("/getDhkhTop10")
    public Result getDhkhTop10(String startDt,String endDt) {
        return Result.success(xCompanyService.getDhkhTop10(startDt,endDt));
    }

    /**
     * 高优先级客户个数
     */
    @GetMapping("/getTopPriority")
    public Result getTopPriority(String startDt,String endDt) {
        return Result.success(xCompanyService.getTopPriority(startDt,endDt));
    }

    /**
     * bd拜访客户次数
     */
    @GetMapping("/getBdbfCount")
    public Result getBdbfCount(String startDt,String endDt) {
        return Result.success(xCompanyService.getBdbfCount(startDt,endDt));
    }

    /**
     * bd看护与发布的大模型个数
     */
    @GetMapping("/getBdBigModelCount")
    public Result getBdBigModelCount(String startDt,String endDt) {
        return Result.success(xCompanyService.getBdBigModelCount(startDt,endDt));
    }

    /**
     * 200dk库存
     */
    @GetMapping("/get200DkInventory")
    public Result get200DkInventory(String startDt,String endDt) {
        return Result.success(xCompanyService.get200DkInventory(startDt,endDt));
    }


}

